package com.nit.bike.mapper.bike;

import com.nit.bike.dto.bike.CardDTO;
import com.nit.bike.entity.bike.CardEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface CardMapper {
    int deleteByPrimaryKey(Long cardId);

    int insert(CardEntity record);

    int insertSelective(CardEntity record);

    CardEntity selectByPrimaryKey(Long cardId);

    int updateByPrimaryKeySelective(CardEntity record);

    int updateByPrimaryKey(CardEntity record);

    /**
     * 查询人员绑定的租借卡
     */
    @Select("SELECT * " +
            "FROM basic_card c " +
            "RIGHT JOIN basic_user u ON c.user_id = u.user_id AND c.card_id = u.card_id " +
            "WHERE u.user_id = #{userId} AND c.card_state = 0 " +
            "LIMIT 1")
    CardDTO queryByUserId(@Param("userId") Long userId) throws Exception;

    /**
     * 查询人员绑定的最后一张租借卡
     */
    @Select("SELECT * " +
            "FROM basic_card c " +
            "JOIN basic_user u ON c.card_id = u.card_id " +
            "WHERE u.user_id = #{userId} AND c.card_state = 1 " +
            "LIMIT 1")
    CardDTO queryLastCard(@Param("userId") Long userId) throws Exception;

    /**
     * 插入数据后立刻查询
     */
    @Select("SELECT LAST_INSERT_ID()")
    Long queryCardId() throws Exception;

    /**
     * 插入数据后立刻更新卡号
     */
    @Update("UPDATE basic_card c " +
            "SET card_number = #{cardNumber} " +
            "WHERE card_id = #{cardId} LIMIT 1")
    void updateCardNumber(
            @Param("cardId") Long cardId,
            @Param("cardNumber") String cardNumber) throws Exception;

    /**
     * 挂失租借卡
     */
    @Update("UPDATE basic_card c " +
            "SET card_state = 1 " +
            "WHERE card_id = #{cardId} LIMIT 1")
    Integer updateState(@Param("cardId") Long cardId) throws Exception;

    /**
     * 更新租借卡数据
     */
    @Update("<script>" +
            "UPDATE basic_card c SET " +
            "<if test='entity.distance != null'>distance = distance + #{entity.distance}, </if>" +
            "<if test='entity.during != null'>during = during + #{entity.during}, </if>" +
            "balance = balance + #{entity.balance} " +
            "WHERE card_id = #{entity.cardId} LIMIT 1" +
            "</script>")
    Integer updateData(@Param("entity") CardEntity entity) throws Exception;
}
